#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "../inc/tcp.h"
#include "../inc/msg_popup.h"
#include "../inc/login.h"
#include "../inc/homepage.h"
#include "../inc/cJSON.h"
#include "../inc/user_event.h"
#include "../inc/weather.h"

static void handle_register_response(int code, const char * message);
static void handle_login_response(int code, const char * message);
static void handle_private_chat_response(int code, const char * message, const char * response);
static void handle_chat_room_response(int code, const char * message, const char * response);
static void handle_join_chat_room_response(int code, const char * message);
static void handle_get_friend_list_response(int code, const char * message, const char * response);
static void handle_add_friend_response(int code, const char * message);
static void handle_get_friend_apply_list_response(int code, const char * message, const char * response);
static void handle_friend_apply_action_response(int code, const char * message);
static void parse_chat_message(const char * json_str, char * text, char * name);
static void handle_logout_response(int code, const char * message);

/**
 * 2. 解析服务器返回的 JSON 格式响应
 * 服务器响应 JSON 结构示例：
 * - 成功：{"type":"login","code":0,"message":"登录成功!"}
 * - 失败：{"type":"register","code":1,"message":"用户名已存在"}
 */
void parse_server_response(const char * response)
{
    // 2.1 解析 JSON 字符串，创建根对象
    cJSON * root = cJSON_Parse(response);
    if(root == NULL) {
        const char * err_msg = cJSON_GetErrorPtr();
        if(err_msg != NULL) {
            printf("JSON 解析失败：在 %s 处格式错误\n", err_msg);
        }
        show_msg_box("服务器响应格式错误", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        cJSON_Delete(root); // 释放无效对象，避免内存泄漏
        return;
    }

    cJSON * type_json = cJSON_GetObjectItem(root, "type");

    cJSON * code_json = cJSON_GetObjectItem(root, "code");
    cJSON * msg_json  = cJSON_GetObjectItem(root, "message");

    printf("服务器响应：%s\n", response);
    // 检查字段是否存在且类型正确
    if(type_json == NULL || !cJSON_IsString(type_json)) {
        printf("JSON 响应缺少必要字段或类型错误\n");
        show_msg_box("服务器响应数据异常", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        cJSON_Delete(root);
        return;
    }

    const char * type = type_json->valuestring;

    printf("收到服务器响应: 类型=%s\n", type);
    if(strcmp(type, "weather") == 0) {
        handle_weather_response(response);
        return;
    }

    if(code_json == NULL || !cJSON_IsNumber(code_json) || msg_json == NULL || !cJSON_IsString(msg_json)) {
        printf("JSON 响应缺少必要字段或类型错误\n");
        show_msg_box("服务器响应数据异常", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        cJSON_Delete(root);
        return;
    }

    // 提取字段值
    int code             = code_json->valueint;
    const char * message = msg_json->valuestring;

    printf("收到服务器响应: 类型=%s, 代码=%d, 消息=%s\n", type, code, message);

    //  分发到对应处理函数
    if(strcmp(type, "register") == 0) {
        handle_register_response(code, message);
    } else if(strcmp(type, "login") == 0) {
        handle_login_response(code, message);
    } else if(strcmp(type, "private_chat") == 0) {
        handle_private_chat_response(code, message, response);
    } else if(strcmp(type, "chat_room") == 0) {
        handle_chat_room_response(code, message, response);
    } else if(strcmp(type, "join_chat_room") == 0) {
        handle_join_chat_room_response(code, message);
    } else if(strcmp(type, "get_friendList") == 0) {
        handle_get_friend_list_response(code, message, response);
    } else if(strcmp(type, "add_friend") == 0) {
        handle_add_friend_response(code, message);
    } else if(strcmp(type, "get_friend_apply_list") == 0) {
        handle_get_friend_apply_list_response(code, message, response);
    } else if(strcmp(type, "friend_apply_action") == 0) {
        handle_friend_apply_action_response(code, message);
    } else if(strcmp(type, "log_out") == 0) {
        handle_logout_response(code, message);
    }

    else {
        printf("未知的响应类型: %s\n", type);
        show_msg_box("未知的服务器响应类型", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
    }

    cJSON_Delete(root);
}

// 处理注册响应
static void handle_register_response(int code, const char * message)
{
    switch(code) {
        case REG_SUCCESS:
            if(register_popup != NULL) lv_obj_del(register_popup);
            show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            break;
        case REG_ERROR_USER_EXISTS: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case REG_ERROR_DB: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case REG_ERROR_USERID_LONG: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case REG_ERROR_EMPTY_INPUT:
            show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            break; // 原代码漏了 break，此处补充
        case REG_ERROR_PASSWORD_FORMAT: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_LONG); break;
        default: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
    }
}

// 处理登录响应
static void handle_login_response(int code, const char * message)
{
    switch(code) {
        case LOGIN_SUCCESS:
            if(login_src != NULL) {
                lv_obj_add_flag(login_src, LV_OBJ_FLAG_HIDDEN); // 隐藏登录界面
            }
            homepage_init();
            get_friend_list();
            pack_get_friend_apply_list_json_request(); // 发送获取好友申请列表的请求
            // show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);  // 登录成功提示框
            return;
        case LOGIN_ERROR_USER_NOT_EXIST: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case LOGIN_ERROR_PASSWORD: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case LOGIN_ERROR_DB: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case LOGIN_ERROR_EMPTY_INPUT: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case LOGIN_ERROR_ALREADY_LOGGED: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_LONG); break;
        default: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
    }
}

static void handle_private_chat_response(int code, const char * message, const char * response)
{
    char name[32];
    char text[256];
    switch(code) {
        // case PRIVATE_CHAT_SUCCESS_RECV_FROM_CLIENT: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        // break;
        case PRIVATE_CHAT_SUCCESS:
            parse_chat_message(response, text, name);
            otherChatBubble(chat_window, text, name);
            break;
        case PRIVATE_CHAT_ERROR_DB: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case PRIVATE_CHAT_ERROR_PARAM: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
    }
}

static void handle_chat_room_response(int code, const char * message, const char * response)
{
    char name[32];
    char text[256];
    switch(code) {
        // case CHATROOM_CHAT_SUCCESS_RECV_FROM_CLIENT: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        // break;
        case CHATROOM_CHAT_SUCCESS_SENDER:
            parse_chat_message(response, text, name);
            // printf("%s", user_event.type);
            if(strcmp(user_event.type, "chat_room") == 0)
                otherChatBubble(chat_window, text, name); // 显示对方的聊天气泡
            // show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            break;
        case CHATROOM_CHAT_ERROR_DB: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case CHATROOM_CHAT_ERROR_PARAM: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
    }
}

static void handle_join_chat_room_response(int code, const char * message)
{
    switch(code) {
        // case 0: show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT); break;
        case 1:
            if(strcmp(user_event.type, "chat_room") == 0) show_chatroom_join_exit_tag(chat_window, message);
            break;
    }
}

static void handle_get_friend_list_response(int code, const char * message, const char * response)
{
    FriendList_t * friendList = (FriendList_t *)malloc(sizeof(FriendList_t));
    if(friendList == NULL) {
        printf("FriendList 内存分配失败\n");
        return;
    }
    memset(friendList, 0, sizeof(FriendList_t)); // 初始化

    switch(code) {
        case 0:
            parse_friend_list(response, friendList);
            show_friend_list(friend_list_box, friendList);
            free(friendList); // 释放结构体本身（仅占指针和计数的内存）
            break;
        case 1:
            show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            free(friendList); // 失败时也要释放结构体
            break;
    }
}
static void handle_add_friend_response(int code, const char * message)
{
    if(code == ADD_FRIEND_SUCCESS || code == ADD_FRIEND_PENDING_APPLY) {
        show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_LONGLONG);
    } else if(code == ADD_FRIEND_ALREADY_FRIEND) {
        show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_LONG);
    } else {
        show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
    }
}

static void handle_get_friend_apply_list_response(int code, const char * message, const char * response)
{
    if(code == GET_FRIEND_APPLY_LIST_SUCCESS) {
        FriendApplyList_t temp_list = {0};
        parse_friend_apply_json(response, &temp_list); // 解析JSON数据
        save_friend_apply_to_cache(&temp_list);        // 保存到本地缓存

        if(temp_list.items != NULL) { // 释放临时列表内存
            free(temp_list.items);
            temp_list.items = NULL;
        }
    } else {
        show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
    }
}

static void handle_friend_apply_action_response(int code, const char * message)
{
    if(code == FRIEND_APPLY_SUCCESS) {
        pack_get_friend_apply_list_json_request();
        refresh_friend_apply_list(); // 替换为新增的刷新函数
        get_friend_list();
    } else if(code == FRIEND_APPLY_ALREADY_FRIEND) {
        get_friend_list();
        refresh_friend_apply_list();
    } else {
        show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        // 错误时也建议刷新（防止本地数据与服务器不一致）
        refresh_friend_apply_list();
    }
}
// 解析聊天消息
static void parse_chat_message(const char * json_str, char * text, char * name)
{
    if(json_str == NULL) {
        printf("JSON字符串为空\n");
        return;
    }

    cJSON * root = cJSON_Parse(json_str);
    if(root == NULL) {
        printf("JSON解析失败: %s\n", cJSON_GetErrorPtr());
        return;
    }

    //  解析payload对象
    cJSON * payload = cJSON_GetObjectItem(root, "payload");
    if(payload == NULL || !cJSON_IsObject(payload)) {
        printf("未找到payload字段或类型错误\n");
        cJSON_Delete(root); // 释放内存
        return;
    }

    // 解析sender_userid
    cJSON * sender_userid = cJSON_GetObjectItem(payload, "sender_userid");
    if(sender_userid != NULL && cJSON_IsString(sender_userid) && sender_userid->valuestring != NULL) {
        strcpy(name, sender_userid->valuestring);
    } else {
        printf("未找到有效的sender_userid\n");
    }

    // 解析content
    cJSON * content = cJSON_GetObjectItem(payload, "content");
    if(content != NULL && cJSON_IsString(content) && content->valuestring != NULL) {
        strcpy(text, content->valuestring);
    } else {
        printf("未找到有效的content\n");
    }

    cJSON_Delete(root);
}

static void handle_logout_response(int code, const char * message)
{
    if(code == LOGOUT_STATUS_SUCCESS) {
        if(home_src != NULL) {
            printf("退出登录 隐藏 home_src start\n");
            lv_obj_add_flag(home_src, LV_OBJ_FLAG_HIDDEN); // 隐藏登录界面
        }
        if(login_src != NULL) {
            printf("退出登录 显示 login_src start\n");
            lv_obj_clear_flag(login_src, LV_OBJ_FLAG_HIDDEN);
            printf("退出登录 显示 login_src over\n");
        }
    }
    show_msg_box(message, MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
}
